/********************************************************
 * Filename: TclExecute.java
 * Author: LMU
 * Program: TUnit
 * Description: Adds the ability to execute test script
 * within the console view.  
 * Revision History:
 * 20060904: Initial Revision.  Added header later.  
 * 20061008: Did a little refactoring.  
 * *****************************************************/

package edu.lmu.cs.tUnit.popup.actions;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.MessageConsole;

import edu.lmu.cs.tUnit.log.TUnitLog;
import edu.lmu.cs.tUnit.popup.shell.TclShell;

public class TclExecute implements IObjectActionDelegate {

	MessageConsole console;
	
	/**
	 * Constructor for TclExecute.
	 */
	public TclExecute() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}

	/**
	 * @see IActionDelegate#run(IAction)  
	 */
	public void run(IAction action) {
		IWorkbench wb = PlatformUI.getWorkbench();
		IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
		IWorkbenchPage page = win.getActivePage();
		ISelection selection = page.getSelection();
		
		//the current selection in the navigator view
		selection = page.getSelection(IPageLayout.ID_RES_NAV);
		IStructuredSelection sel = (IStructuredSelection) selection;
		Object element = sel.getFirstElement();
		IResource res = (IResource) element;
		IPath path = res.getLocation();
		
		createTclShell(path);
	}

	/**
	 * Creates the tcl shell
	 * @param path
	 */
	private void createTclShell(IPath path) {
		// get the console view
		ConsolePlugin.getDefault().getConsoleManager().removeConsoles(new IConsole[]{console});
		console = new MessageConsole("Tcl Console", null);
		
		// create a tcl shell
		TclShell tShell = new TclShell("\"" + path.toString() + "\"", console, path.toFile().getParent());
		Shell shell = new Shell();
		int failures = tShell.getFailures();
		
		TclMessageDialog dialog = new TclMessageDialog(shell, SWT.APPLICATION_MODAL, failures);
		dialog.open();
		TUnitLog.logInfo("Run completed with " + failures + " failures.");
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
	}
}
